/**
 * Project Name:HomeActivity
 * Date:2016-2-23下午12:36:16
 * Copyright (c) 2016, askzhao All Rights Reserved.
 *
 */
package com.kkd.kkdapp.fragment;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.activity.CurrentTenderActivity;
import com.kkd.kkdapp.activity.EvetyDayJoinRecordActivity;
import com.kkd.kkdapp.activity.ForTenderActivity;
import com.kkd.kkdapp.activity.KKDWebActivity;
import com.kkd.kkdapp.activity.LoginActivity;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.CurUserModel;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.http.entity.EveryDayData;
import com.kkd.kkdapp.http.entity.EveryDayData1;
import com.kkd.kkdapp.http.entity.EveryDayYuebao;
import com.kkd.kkdapp.http.entity.YueBaoAdEntity;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.utils.Time_Date;
import com.kkd.kkdapp.view.KkdListHeader;
import com.kkd.kkdapp.view.MyRelativeLayout.OnItemClick;
import com.kkd.kkdapp.view.MyRoundProgressBar;
import com.kkd.kkdapp.view.RiseNumberTextView;
import com.kkd.kkdapp.view.ScrollViewContainer;
import com.kkd.kkdapp.view.ScrollerLayout;
import com.kkd.kkdapp.view.ScrollerLayout.OnPullListener;
import com.kkd.kkdapp.view.ScrollerLayout.ScrollStateProvider;
import com.kkd.kkdapp.view.xlistview.XListViewHeader;
import com.nostra13.universalimageloader.core.ImageLoader;

public class CurrentFragment extends Fragment implements OnClickListener {

	private final int YUEBAO_CODE_ZERO = 1; // 天天赚code=0
	private final int YUEBAO_CODE_ELSE = 2; // 天天赚code=其它
	private String url; // html5url
	private String isPost = "no";

	private long buyFreeAmountSum; // 已购买金额
	private String bidProgress;
	private int buyNumSum; // 购买人数
	private double rates; // 日收益计算
	private int interest; // 利率
	private long amount; // 总额
	private String title; // 标题
	private String yuebaoid; // 天天赚ID
	private String surplus;// 剩余额度
	private long lowestAmount;
	private boolean btflag;

	public int maxTime = 0;
	private int mRecordTime = 0;
	private boolean isRecoding = false;
	private TimerTask mTimerTask = null;
	private Timer mTimer = new Timer();
	public static final int PERIOD = 1000;
	public static final int RECORD_TIMER = 8112;
	public static final int RECORD_DONE = 8113;
	public static final int RECORD_ERROR = 8114;
	private boolean flag2WebActivity = false;

	private View mContentView;
	public TimerHandler mTimerHandler = new TimerHandler(this);
	private Dialog viewPagerDialog;
	private MyRoundProgressBar progressbar_current_fragment;
	private ScrollerLayout mScrollView;
	private KkdListHeader mHeaderView;
	private RelativeLayout mHeaderViewContent;
	// private TextView mHeaderTimeView;
	private TextView title_tv_current_fragment;
	private Handler mHandler = new Handler();
	private Button purchase_bt_current_fragment;
	private Intent intent;
	private double balance;
	private RelativeLayout share_current_fragment;
	private RelativeLayout joinRecord_rel;
	private TextView totalMoney_tv_current_fragment;
	private TextView canBuy_tv_current_fragment;
	private TextView buyProgress_tv_current_fragment;
	private RiseNumberTextView interest_current_fragment;
	private TextView num_top_tv_current_fragment;
	private TextView join_tv2_current;
	private ScrollViewContainer scrollViewContainer_currentFragment;
	private ImageView img_null_currentFragment;
	private TextView tv_null_currentFragment;
	private LinearLayout linear1_current;
	private LinearLayout linear2_current;
	private LinearLayout linear3_current;
	private LinearLayout linear4_current;
	private ImageView iv1_current;
	private ImageView iv2_current;
	private ImageView iv3_current;
	private ImageView iv4_current;
	private TextView tv1_current;
	private TextView tv2_current;
	private TextView tv3_current;
	private TextView tv4_current;
	private WebView mWebView;

	private EveryDayData data;
	private List<YueBaoAdEntity> list_ad;
	private List<ImageView> list_ad_imageView = new ArrayList<ImageView>();
	private List<TextView> list_ad_textView = new ArrayList<TextView>();
	private List<Integer> list_defaultImages = new ArrayList<Integer>();
	private DecimalFormat df = new DecimalFormat("0.00");
	private DecimalFormat df1 = new DecimalFormat("#,###");
	private DecimalFormat df2 = new DecimalFormat("#,###.00");
	private String[] imaIdArray;
	private String[] textArray;
	private String title_xieYi = "";
	private String url_xieYi = "";
	private boolean isHaveXieyi = true;
	private boolean isCanTender = true;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			String desc = "";

			switch (msg.what) {
			case YUEBAO_CODE_ZERO: // 天天赚code=0
				renewalUI();
				imaIdArray = new String[list_ad.size()];
				textArray = new String[list_ad.size()];
				if (list_ad != null && list_ad.size() > 0) {
					for (int i = 0; i < list_ad.size(); i++) {
						list_ad_textView.get(i).setText(
								list_ad.get(i).getTitle());
						ImageLoader.getInstance().displayImage(
								list_ad.get(i).getImageUrl(),
								list_ad_imageView.get(i),
								list_defaultImages.get(i));
						imaIdArray[i] = list_ad.get(i).getImageBigUrl();
						textArray[i] = list_ad.get(i).getTitleBig();
					}
				}
				scrollViewContainer_currentFragment.setVisibility(View.VISIBLE);
				img_null_currentFragment.setVisibility(View.GONE);
				tv_null_currentFragment.setVisibility(View.GONE);
				break;
			case YUEBAO_CODE_ELSE:
				desc = (String) msg.obj;
				scrollViewContainer_currentFragment.setVisibility(View.GONE);
				img_null_currentFragment.setVisibility(View.VISIBLE);
				tv_null_currentFragment.setVisibility(View.VISIBLE);
				showToast(desc);
				break;
			case 3:
				desc = (String) msg.obj;
				showToast(desc);
				break;
			default:
				break;
			}
		};
	};

	public static class TimerHandler extends Handler {
		WeakReference<CurrentFragment> reference;

		public TimerHandler(CurrentFragment fragment) {
			reference = new WeakReference<CurrentFragment>(fragment);
		}

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case RECORD_TIMER:
				if (reference != null && reference.get() != null)
					reference.get().updatePurchaseBtn();
				break;
			case RECORD_DONE:
				if (reference != null && reference.get() != null)
					reference.get().onTimerFinish();
				break;
			default:
				break;
			}
		}
	}

	BaseActivity mCurActivity;
	private TextView tv_xieyi_everyday;
	private View rel_selectXieyi;
	private ImageView iv_selectXieyi;
	private TextView hint_tv;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onAttach(android.app.Activity)
	 */
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mCurActivity = (BaseActivity) activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContentView = inflater.inflate(R.layout.fragment_current, container,
				false);
		initView();
		initListener();
		return mContentView;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (!flag2WebActivity) {
			requestYuebao();
			if (PreferenceUtils.getInstance().getLogin(getActivity()) == 0) {
				getAccountInfo();
			}
		} else {
			flag2WebActivity = false;
		}
	}

	private void initView() {
		// 标题栏
		title_tv_current_fragment = (TextView) mContentView
				.findViewById(R.id.title_tv_current_fragment);
		mContentView.findViewById(R.id.title_img_current_fragment)
				.setOnClickListener(this);
		// 提示
		hint_tv = (TextView) mContentView.findViewById(R.id.hint_tv);
		// 初始化下拉刷新
		mScrollView = (ScrollerLayout) mContentView
				.findViewById(R.id.scrollerLayout_current_fragment);
		mHeaderView = new KkdListHeader(getActivity());
		mHeaderViewContent = (RelativeLayout) mHeaderView
				.findViewById(R.id.xlistview_header_content);
		// mHeaderTimeView = (TextView) mHeaderView
		// .findViewById(R.id.xlistview_header_time);
		mScrollView.addTopView(mHeaderView);
		// 分享
		share_current_fragment = (RelativeLayout) mContentView
				.findViewById(R.id.share_current_fragment);
		// scrollViewContainer
		scrollViewContainer_currentFragment = (ScrollViewContainer) mContentView
				.findViewById(R.id.scrollViewContainer_currentFragment);
		// 进度条
		progressbar_current_fragment = (MyRoundProgressBar) mContentView
				.findViewById(R.id.progressbar_current_fragment);
		// 天天赚期数
		num_top_tv_current_fragment = (TextView) mContentView
				.findViewById(R.id.num_top_tv_current_fragment);
		// 利率
		interest_current_fragment = (RiseNumberTextView) mContentView
				.findViewById(R.id.interest_current_fragment);
		// 项目总额
		totalMoney_tv_current_fragment = (TextView) mContentView
				.findViewById(R.id.totalMoney_tv_current_fragment);
		// 可购买金额
		canBuy_tv_current_fragment = (TextView) mContentView
				.findViewById(R.id.canBuy_tv_current_fragment);
		// 认购进度
		buyProgress_tv_current_fragment = (TextView) mContentView
				.findViewById(R.id.buyProgress_tv_current_fragment);

		// 认购
		purchase_bt_current_fragment = (Button) mContentView
				.findViewById(R.id.purchase_bt_current_fragment);
		// 跳转到天天赚协议
		tv_xieyi_everyday = (TextView) mContentView
				.findViewById(R.id.tv_xieyi_everyday);
		// 是否勾选协议
		rel_selectXieyi = mContentView.findViewById(R.id.rel_selectXieyi);
		iv_selectXieyi = (ImageView) mContentView
				.findViewById(R.id.iv_selectXieyi);
		// 加入记录
		joinRecord_rel = (RelativeLayout) mContentView
				.findViewById(R.id.joinRecord_rel);
		// 购买人数
		join_tv2_current = (TextView) mContentView
				.findViewById(R.id.join_tv2_current);
		// 网络异常提示
		img_null_currentFragment = (ImageView) mContentView
				.findViewById(R.id.img_null_currentFragment);
		tv_null_currentFragment = (TextView) mContentView
				.findViewById(R.id.tv_null_currentFragment);
		// 4张logo图的linear
		linear1_current = (LinearLayout) mContentView
				.findViewById(R.id.linear1_current);
		linear2_current = (LinearLayout) mContentView
				.findViewById(R.id.linear2_current);
		linear3_current = (LinearLayout) mContentView
				.findViewById(R.id.linear3_current);
		linear4_current = (LinearLayout) mContentView
				.findViewById(R.id.linear4_current);
		// 4张logo图的imageview
		iv1_current = (ImageView) mContentView.findViewById(R.id.iv1_current);
		iv2_current = (ImageView) mContentView.findViewById(R.id.iv2_current);
		iv3_current = (ImageView) mContentView.findViewById(R.id.iv3_current);
		iv4_current = (ImageView) mContentView.findViewById(R.id.iv4_current);
		list_ad_imageView.add(iv1_current);
		list_ad_imageView.add(iv2_current);
		list_ad_imageView.add(iv3_current);
		list_ad_imageView.add(iv4_current);
		// 4张logo图的textview
		tv1_current = (TextView) mContentView.findViewById(R.id.tv1_current);
		tv2_current = (TextView) mContentView.findViewById(R.id.tv2_current);
		tv3_current = (TextView) mContentView.findViewById(R.id.tv3_current);
		tv4_current = (TextView) mContentView.findViewById(R.id.tv4_current);
		list_ad_textView.add(tv1_current);
		list_ad_textView.add(tv2_current);
		list_ad_textView.add(tv3_current);
		list_ad_textView.add(tv4_current);
		list_defaultImages.add(R.drawable.shouyi_current);
		list_defaultImages.add(R.drawable.shuishichunqu_current);
		list_defaultImages.add(R.drawable.shouyifutou_current);
		list_defaultImages.add(R.drawable.zijinbaozhang_current);
		// 详情页的webview
		mWebView = (WebView) mContentView
				.findViewById(R.id.webView_currentFragment);
		RelativeLayout title_current_fragment = (RelativeLayout) mContentView
				.findViewById(R.id.title_current_fragment);
		TextView title_tv_current_fragment = (TextView) mContentView
				.findViewById(R.id.title_tv_current_fragment);
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
			RelativeLayout.LayoutParams ly = new RelativeLayout.LayoutParams(
					LayoutParams.FILL_PARENT, SystemUtils.dip2px(getActivity(),
							50f));
			title_current_fragment.setLayoutParams(ly);
			title_tv_current_fragment.setPadding(0, 0, 0, 0);
		}
		initWeb();
	}

	private void initListener() {
		share_current_fragment.setOnClickListener(this);
		purchase_bt_current_fragment.setOnClickListener(this);
		tv_xieyi_everyday.setOnClickListener(this);
		rel_selectXieyi.setOnClickListener(this);
		joinRecord_rel.setOnClickListener(this);
		linear1_current.setOnClickListener(this);
		linear2_current.setOnClickListener(this);
		linear3_current.setOnClickListener(this);
		linear4_current.setOnClickListener(this);
		// 下拉刷新
		mScrollView.setScrollStateProvider(new ScrollStateProvider() {

			@Override
			public boolean canPullUp() {
				return false;
			}

			@Override
			public boolean canPullDown() {
				// ScrollView nScrollView = (ScrollView) mScrollView
				// .findViewById(R.id.scrollView1_current_fragment);
				// int scrollY = nScrollView.getScrollY();
				if (ScrollViewContainer.flag_canDown == 0) {
					return true;
				}
				return false;
			}
		});
		mScrollView.setOnPullListener(new OnPullListener() {

			@Override
			public void onPullUp(float pull) {

			}

			@Override
			public void onPullStateChange(byte state) {

				switch (state) {
				case ScrollerLayout.STATUS_IDLE:// 空闲状态
					mHeaderView.setVisibility(View.GONE);
					break;
				case ScrollerLayout.STATUS_PULL_DOWN:// 下拉：不满足hold条件
					mHeaderView.setVisibility(View.VISIBLE);
					mHeaderView.setState(XListViewHeader.STATE_NORMAL);
					break;
				case ScrollerLayout.STATUS_PULL_UP:// 上拉：不满足hold条件
					break;
				case ScrollerLayout.STATUS_UP_HOLD:// 上拉后等待状态
					break;
				case ScrollerLayout.STATUS_DOWN_HOLD:// 下拉后等待状态
					mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
					mHandler.post(new Runnable() {

						@Override
						public void run() {

							if (AppUtil.isConnect(getActivity())) {
								requestYuebao();
								if (PreferenceUtils.getInstance().getLogin(
										getActivity()) == 0) {
									getAccountInfo();
								}
							} else {
								showToast("网络连接失败！");
							}

							Time_Date time_Date = new Time_Date();
							String time = time_Date.get_Year_Day();
							// mHeaderTimeView.setText(time);
							mHeaderView.setState(XListViewHeader.STATE_NORMAL);
							mHeaderView.setVisibility(View.GONE);

							mScrollView.clearState();
						}
					});
					break;
				case ScrollerLayout.STATUS_ANIMATING:// 回弹动画状态
					break;
				case ScrollerLayout.STATUS_PULL_DOWN_ENABLE:// 下拉：满足hold条件，松开将hold
					mHeaderView.setState(XListViewHeader.STATE_READY);
					break;
				case ScrollerLayout.STATUS_PULL_UP_ENABLE: // 上拉：满足hold条件，松开将hold
					break;
				default:
					break;
				}

			}

			@Override
			public void onPullDown(float pull) {

			}
		});
	}

	/**
	 * 天天赚详情
	 */
	private void requestYuebao() {
		if (mWebView.canGoBack()) {
			mWebView.goBack();
		}
		// KkdHttpMagager.getInstance().getEveryDayManager(EveryDayData.class,
		// new HttpCallBack() {
		//
		// @Override
		// public void onSuccess(int statusCode, Object responseBody) {
		// data = (EveryDayData) responseBody;
		// list_ad = data.getYuebaoProperty();
		// url = data.getYuebaoDetailUrl();
		// title_xieYi = data.getYuebaoXy().getTitle();
		// tv_xieyi_everyday.setText(title_xieYi);
		// url_xieYi = data.getYuebaoXy().getUrl();
		// // 展示天天赚下架信息
		// if (TextUtils.isEmpty(data.getStopInfo().getDesc())) {
		// hint_tv.setVisibility(View.GONE);
		// } else {
		// hint_tv.setText(data.getStopInfo().getDesc());
		// hint_tv.setVisibility(View.VISIBLE);
		// }
		// if (data.getStopInfo().getStatus() == 0) { // 不可转入
		// isCanTender = false;
		// } else {
		// isCanTender = true;
		// }
		// loadWeb();
		// handler.sendEmptyMessage(YUEBAO_CODE_ZERO);
		// }
		//
		// @Override
		// public void onFailure(int statusCode, String desc) {
		// Message msg = new Message();
		// msg.what = YUEBAO_CODE_ELSE;
		// msg.obj = desc;
		// handler.sendMessage(msg);
		// }
		// });

	}

	public void requestLayout() {
		progressbar_current_fragment.setSw(0);
		progressbar_current_fragment.requestLayout();
		interest_current_fragment.withNumber((float) interest / 100);
		// 设置动画播放时间
		interest_current_fragment.setDuration(500);
		// 开始播放动画
		interest_current_fragment.start();
		interest_current_fragment.setText("" + buyNumSum);
	}

	public void renewalUI() {
		EveryDayData1 data1 = data.getData();
		buyFreeAmountSum = data1.getBuyFreeAmountSum(); // 购买金额
		bidProgress = data1.getBidProgress();
		buyNumSum = data1.getBuyNumSum();
		rates = data1.getRates(); // 日收益计算
		EveryDayYuebao yuebao = data.getYuebao();
		interest = yuebao.getInterest(); // 利率
		amount = yuebao.getAmount(); // 总金额
		title = yuebao.getTitle(); // 标题
		yuebaoid = yuebao.getYuebaoId(); // 天天赚ID
		lowestAmount = yuebao.getLowestAmount();
		surplus = df2.format((amount - buyFreeAmountSum) * 0.01)
				.startsWith(".") ? ("0" + df2
				.format((amount - buyFreeAmountSum) * 0.01)) : df2
				.format((amount - buyFreeAmountSum) * 0.01);
		canBuy_tv_current_fragment.setText(surplus);
		title_tv_current_fragment.setText(title);
		num_top_tv_current_fragment.setText(title);
		totalMoney_tv_current_fragment.setText(df1.format(amount / 100) + "元");
		buyProgress_tv_current_fragment.setText(bidProgress + "%");
		join_tv2_current.setText(buyNumSum + "");
		if (((double) buyFreeAmountSum / amount * 100) < 1
				&& ((double) buyFreeAmountSum / amount * 100) > 0) {
			progressbar_current_fragment.setProgress(1);
		} else {
			progressbar_current_fragment
					.setProgress((int) ((double) buyFreeAmountSum / amount * 100));
		}
		// mMyRoundProgressBar.setInterestRate((double) interest / 100);
		// 设置数据
		interest_current_fragment.withNumber((float) interest / 100);
		// 设置动画播放时间
		interest_current_fragment.setDuration(500);
		// 开始播放动画
		interest_current_fragment.start();
		interest_current_fragment.setText("" + buyNumSum);

		purchase_bt_current_fragment.setAlpha(1.0f);
		purchase_bt_current_fragment
				.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

		if (isCanTender) {
			if ((double) (amount - buyFreeAmountSum) * 0.01 == 0) {
				if (isHaveXieyi) {
					purchase_bt_current_fragment.setEnabled(true);
				} else {
					purchase_bt_current_fragment.setEnabled(false);
				}
				btflag = false;
			} else {
				if (isHaveXieyi) {
					purchase_bt_current_fragment.setEnabled(true);
				} else {
					purchase_bt_current_fragment.setEnabled(false);
				}
				btflag = true;
			}
			if (data.getYuEBaoSendTime() > 0) {
				purchase_bt_current_fragment.setAlpha(0.5f);
				purchase_bt_current_fragment.setTextSize(
						TypedValue.COMPLEX_UNIT_SP, 16);
				maxTime = data.getYuEBaoSendTime();
				purchase_bt_current_fragment.setEnabled(false);
				updatePurchaseBtn();
				startTime();
			} else {
				purchase_bt_current_fragment.setAlpha(1.0f);
				purchase_bt_current_fragment.setTextSize(
						TypedValue.COMPLEX_UNIT_SP, 18);
				purchase_bt_current_fragment.setText("转入");
				if (isHaveXieyi) {
					purchase_bt_current_fragment.setEnabled(true);
				} else {
					purchase_bt_current_fragment.setEnabled(false);
				}
			}
		} else {
			purchase_bt_current_fragment.setEnabled(false);
		}
	}

	public void startTime() {
		mRecordTime = 0;
		if (!isRecoding) {
			if (mTimerTask != null) {
				mTimerTask.cancel();
				mTimerTask = null;
			}
			if (mTimer != null) {
				mTimer.cancel();
				mTimer = null;
			}
			mTimerTask = new RecordTimeTask();
			mTimer = new Timer();
			mTimer.schedule(mTimerTask, 0, PERIOD);
		}

		isRecoding = true;

	}

	public void onTimerFinish() {
		requestYuebao();
	}

	public void updatePurchaseBtn() {
		int dtime = maxTime - mRecordTime;
		int ss = dtime % 60;
		int mm = (dtime / 60) % 60;
		int hh = dtime / 60 / 60;
		String strTime = String.format("%02d 时 %02d 分 %02d 秒", hh, mm, ss);
		purchase_bt_current_fragment.setText("距下期更新: " + strTime);

	}

	private void initWeb() {
		WebSettings webSettings = mWebView.getSettings();
		// 设置WebView属性，能够执行Javascript脚本
		webSettings.setJavaScriptEnabled(true);
		mWebView.getSettings().setDefaultTextEncodingName("utf-8");
		// 设置可以访问文件
		webSettings.setAllowFileAccess(true);
		// 设置支持缩放
		webSettings.setBuiltInZoomControls(false);
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		// 设置Web视图
		mWebView.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				return true;
			}
		});
		mWebView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url.startsWith("tel:")) {
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);
				} else if (url.startsWith("http:") || url.startsWith("https:")) {
					// view.loadUrl(url);
					if (!TextUtils.isEmpty(url)) {
						Intent intent = new Intent(getActivity(),
								KKDWebActivity.class);
						intent.putExtra("url", url);
						if (url.contains("apphistory")) {
							intent.putExtra("titleName", "往期天天赚");
						} else {
							intent.putExtra("titleName", "产品协议");
						}
						startActivity(intent);
					}
					flag2WebActivity = true;
				}
				return true;
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				// mWebView.loadUrl("file:///android_asset/rate.html");
			};

			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				handler.proceed();
			}
		});
		mWebView.setWebChromeClient(new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				return super.onJsAlert(view, url, message, result);
			}

			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				LogUtil.e("newProgress", "" + newProgress);
			}

		});
	}

	private void loadWeb() {
		mWebView.clearHistory();
		// 加载需要显示的网页
		if (!TextUtils.isEmpty(isPost) && isPost.equals("yes")) {
			User user = CurUserModel.getCurUser();
			if (user != null) {
				String postdata = "customerId=" + user.customerId + "&token="
						+ user.token + "&channel=Android";
				mWebView.postUrl(url, postdata.getBytes());
			} else {
				String postdata = "customerId=&token=&channel=Android";
				mWebView.postUrl(url, postdata.getBytes());
			}
		} else {
			mWebView.loadUrl(url);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_img_current_fragment:
			getActivity().finish();
			break;

		case R.id.linear1_current:
			if (imaIdArray != null && imaIdArray.length > 0) {
				showViewPagerDialog(1, imaIdArray, textArray);
			}
			break;

		case R.id.linear2_current:
			if (imaIdArray != null && imaIdArray.length > 0) {
				showViewPagerDialog(2, imaIdArray, textArray);
			}
			break;

		case R.id.linear3_current:
			if (imaIdArray != null && imaIdArray.length > 0) {
				showViewPagerDialog(3, imaIdArray, textArray);
			}
			break;

		case R.id.linear4_current:
			if (imaIdArray != null && imaIdArray.length > 0) {
				showViewPagerDialog(4, imaIdArray, textArray);
			}
			break;

		case R.id.purchase_bt_current_fragment:// 认购
			SystemUtils.onEvent("Current_TransferIN", 1);
			if (btflag) {
				if (AppUtil.isConnect(getActivity())) {
					if (PreferenceUtils.getInstance().getLogin(getActivity()) == 0) { // 登陆验证
						if (PreferenceUtils.getInstance().getAutonym(
								getActivity()) == 1) { // 身份认证
							if (PreferenceUtils.getInstance().getBoundBankCard(
									getActivity()) == 1) { // 判定银行卡是否绑定
								intent = new Intent(getActivity(),
										CurrentTenderActivity.class);
								// intent = new Intent(getActivity(),
								// EveryDayTenderActivity.class);
								intent.putExtra("title", title);
								intent.putExtra("surplus", surplus);
								intent.putExtra("yuebaoid", yuebaoid);
								intent.putExtra("lowestAmount", lowestAmount);
								String interests = df.format(interest * 0.01);
								intent.putExtra("interests", interests);
								intent.putExtra("rates", rates);
								intent.putExtra("url_xieYi", url_xieYi);
								intent.putExtra("title_xieYi", title_xieYi);
								getActivity().startActivity(intent);
							} else {
								if (balance == 0) {
									intent = new Intent(getActivity(),
											ForTenderActivity.class);
									intent.putExtra("enterTypeFlag", 4);
									intent.putExtra("title", title);
									intent.putExtra("surplus", surplus);
									intent.putExtra("yuebaoid", yuebaoid);
									intent.putExtra("lowestAmount",
											lowestAmount);
									String interests = df
											.format(interest * 0.01);
									intent.putExtra("interests", interests);
									intent.putExtra("rates", rates);
									intent.putExtra("url_xieYi", url_xieYi);
									intent.putExtra("title_xieYi", title_xieYi);
									getActivity().startActivity(intent);
								} else {
									intent = new Intent(getActivity(),
											CurrentTenderActivity.class);
									// intent = new Intent(getActivity(),
									// EveryDayTenderActivity.class);
									intent.putExtra("title", title);
									intent.putExtra("surplus", surplus);
									intent.putExtra("yuebaoid", yuebaoid);
									intent.putExtra("lowestAmount",
											lowestAmount);
									String interests = df
											.format(interest * 0.01);
									intent.putExtra("interests", interests);
									intent.putExtra("rates", rates);
									intent.putExtra("url_xieYi", url_xieYi);
									intent.putExtra("title_xieYi", title_xieYi);
									getActivity().startActivity(intent);
								}
							}
						} else {
							intent = new Intent(getActivity(),
									ForTenderActivity.class);
							intent.putExtra("isShowDialogTip", false);
							intent.putExtra("enterTypeFlag", 4);
							intent.putExtra("title", title);
							intent.putExtra("surplus", surplus);
							intent.putExtra("yuebaoid", yuebaoid);
							intent.putExtra("lowestAmount", lowestAmount);
							String damount = df.format(amount * 0.01);
							intent.putExtra("amount", damount);
							intent.putExtra("rates", rates);
							String interests = df.format(interest * 0.01);
							intent.putExtra("interests", interests);
							intent.putExtra("url_xieYi", url_xieYi);
							intent.putExtra("title_xieYi", title_xieYi);
							getActivity().startActivity(intent);
						}
					} else {
						intent = new Intent(getActivity(), LoginActivity.class);
						getActivity().startActivity(intent);
					}
				} else {
					showToast("网络异常，请您检查网络状态！");
				}
			}
			break;
		case R.id.share_current_fragment: // 分享
			mCurActivity.toShareURL(getActivity(),
					com.kkd.kkdapp.Environment.SHARE_ULR + "appDownload.html",
					"快快贷理财", "[快快金融]APP,快快贷致力于打造中国最具专业性的创新型互联网金融综合借贷服务平台 ",
					R.drawable.share_kkdai_logo);
			break;
		case R.id.joinRecord_rel: // 加入记录
			SystemUtils.onEvent("Current_Record", 1);
			intent = new Intent(getActivity(), EvetyDayJoinRecordActivity.class);
			intent.putExtra("yuebaoid", yuebaoid);
			getActivity().startActivity(intent);
			break;

		case R.id.tv_xieyi_everyday: // 跳转天天赚协议
			if (!TextUtils.isEmpty(url_xieYi)) {
				intent = new Intent(mCurActivity, KKDWebActivity.class);
				intent.putExtra("url", url_xieYi);
				getActivity().startActivity(intent);
			}
			break;

		case R.id.rel_selectXieyi: // 勾选协议
			isHaveXieyi = !isHaveXieyi;
			if (isHaveXieyi) {
				iv_selectXieyi.setImageResource(R.drawable.icon_havexieyi);
				if (isCanTender) {
					if (isRecoding) {
						purchase_bt_current_fragment.setEnabled(false);
					} else {
						purchase_bt_current_fragment.setEnabled(true);
					}
				} else {
					purchase_bt_current_fragment.setEnabled(false);
				}
			} else {
				iv_selectXieyi.setImageResource(R.drawable.icon_noxieyi);
				purchase_bt_current_fragment.setEnabled(false);
			}
			break;
		default:
			break;
		}
	}

	private void showViewPagerDialog(int currentItem,
			final String[] imaIdArray, String[] textArray) {
		if (viewPagerDialog != null) {
			viewPagerDialog.cancel();
			viewPagerDialog = null;
		}
		viewPagerDialog = DialogUtils.showCharacteristicDialog(getActivity(),
				currentItem, imaIdArray, textArray, new OnItemClick() {

					@Override
					public void getPosition(int position) {
						if (position == imaIdArray.length - 1) {
							Intent intent = new Intent(getActivity(),
									KKDWebActivity.class);
							intent.putExtra("url",
									com.kkd.kkdapp.Environment.getH5Url()
											+ "appinsurance.html"); // 正式
							intent.putExtra("titleName", "安全保障");
							startActivity(intent);
							if (viewPagerDialog != null) {
								viewPagerDialog.cancel();
								viewPagerDialog = null;
							}
						}
					}
				});
		viewPagerDialog.show();
	}

	private void showToast(String hintLanguage) {
		AppUtil.makeToastForCustomer(getActivity(), hintLanguage);
	}

	private class RecordTimeTask extends TimerTask {
		@Override
		public void run() {
			if (isRecoding) {
				mRecordTime++;
				if (mRecordTime <= maxTime) {
					Message message = new Message();
					message.what = RECORD_TIMER;
					message.obj = mRecordTime;
					mTimerHandler.sendMessage(message);
				} else {
					Message message = new Message();
					message.what = RECORD_DONE;
					message.arg1 = mRecordTime;
					message.obj = "";
					mTimerHandler.sendMessage(message);
					isRecoding = false;
				}
			}

		}
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {

		KkdHttpMagager.getInstance().getAccountInfoManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							balance = data.getDouble("balance");
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = 3;
						msg.obj = desc;
						handler.sendMessage(msg);
					}
				});
	}

	public void ondestroy() {

		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
	}

}
